<template>
  <div>
    <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
      <el-form-item label="是否合同" size="small">
        <el-switch
          v-model="teamRow.isProject"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value=1
          :inactive-value=0
          :disabled="dialogType===0"
        >
        </el-switch>
      </el-form-item>
      <div v-if="teamRow.isProject">
        <el-form-item prop="contractCode" label="合同编号" size="small">
          <el-autocomplete
            v-model="teamRow.contractCode"
            :fetch-suggestions="querySearchProject"
            @select="handleSelectProject"
            placeholder="请输入内容"
            :disabled="dialogType===0"
          >
          </el-autocomplete>
        </el-form-item>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item v-if="teamRow.projectName" label="合同项目" size="small">
              <el-tooltip :content="teamRow.projectName" placement="top-end">
                <span class="nowrap">{{teamRow.projectName}}</span>
              </el-tooltip>
            </el-form-item>
            <el-form-item v-if="teamRow.address" label="项目所属地" size="small">
              <el-tooltip :content="teamRow.address" placement="top-end">
                <span class="nowrap">{{teamRow.address}}</span>
              </el-tooltip>
            </el-form-item>
            <el-form-item v-if="teamRow.contractAmount||teamRow.contractAmount===0" label="合同金额" size="small">
              {{teamRow.contractAmount}}万元
            </el-form-item>
            <el-form-item label="本次尾款" size="small">
              {{balancePay}}万元
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item v-if="teamRow.teamName" label="所属团队" size="small">
              {{teamRow.teamName}}
            </el-form-item>
            <el-form-item v-if="teamRow.partyA" label="业主" size="small">
              <el-tooltip :content="teamRow.partyA" placement="top-end">
                <span class="nowrap">{{teamRow.partyA}}</span>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="项目尾款" size="small">
              {{teamRow.balancePayment||0}}万元
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item prop="billTime" label="收款时间" size="small">
              <el-date-picker
                v-model="teamRow.billTime"
                type="date"
                value-format="timestamp"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item prop="billAmount" label="收款金额" size="small">
              <el-input type="number" v-model.number="teamRow.billAmount">
                <span slot="suffix">万元</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item label="管理费率" size="small">
              <el-input type="number" v-model.number="teamRow.managementPercentage">
                <span slot="suffix">%</span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item label="管理费" size="small">
              {{Math.round(teamRow.managementPercentage * teamRow.billAmount * 10000) / 1000000||0}}万元
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item label="签字费率" size="small">
              {{teamRow.signature||0}}%
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item label="签字费" size="small">
              {{Math.round(teamRow.signature * teamRow.billAmount * 10000) / 1000000||0}}万元
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item label="审核费率" size="small">
              {{teamRow.audit||0}}%
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item label="审核费" size="small">
              {{Math.round(teamRow.audit * teamRow.billAmount * 10000) / 1000000||0}}万元
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item label="其他费率" size="small">
              {{teamRow.other||0}}%
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item label="其他费用" size="small">
              {{Math.round(teamRow.other * teamRow.billAmount * 10000) / 1000000||0}}万元
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item prop="receivingUnit" label="收款单位" size="small">
              <el-select v-model="teamRow.receivingUnit" placeholder="请选择">
                <el-option
                  v-for="item in global.billUnitList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item prop="stage" label="收款阶段" size="small">
              <el-select v-model="teamRow.stage" placeholder="请选择">
                <el-option
                  v-for="item in global.stageList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="row-border" v-if="isBillReceived">
          <el-form-item label="已到账信息" size="small">
          </el-form-item>
          <el-row v-for="item in billReceivedInfo">
            <el-col class="singleDatePicker">
              <el-form-item label="付款阶段" size="small">
                {{item.stage | filterStage}}
              </el-form-item>
            </el-col>
            <el-col class="singleDatePicker">
              <el-form-item label="到账金额" size="small">
                {{item.billAmount}}万元
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!--<el-form-item prop="operator" label="收款人" size="small">
          <el-autocomplete
            v-model="teamRow.operator"
            :fetch-suggestions="querySearchOperator"
            placeholder="请输入内容"
          >
          </el-autocomplete>
        </el-form-item>-->
      </div>
      <div v-else>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item label="项目名称" size="small">
              <el-input type="text" v-model="teamRow.billName">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item prop="teamName" label="所属团队" size="small">
              <el-autocomplete
                v-model="teamRow.teamName"
                :fetch-suggestions="querySearchTeam"
                @select="handleSelectTeam"
                placeholder="请输入内容"
              >
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item prop="billTime" label="收款时间" size="small">
              <el-date-picker
                v-model="teamRow.billTime"
                type="date"
                value-format="timestamp"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item prop="billAmount" label="收款金额" size="small">
              <el-input type="number" v-model.number="teamRow.billAmount">
                <span slot="suffix">万元</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item prop="managementPercentage" label="管理费率" size="small">
              <el-input type="number" v-model.number="teamRow.managementPercentage">
                <span slot="suffix">%</span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item label="管理费" size="small">
              {{Math.round(teamRow.managementPercentage * teamRow.billAmount * 10000) / 1000000||0}}万元
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col class="singleDatePicker">
            <el-form-item prop="receivingUnit" label="收款单位" size="small">
              <el-select v-model="teamRow.receivingUnit" placeholder="请选择">
                <el-option
                  v-for="item in global.billUnitList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col class="singleDatePicker">
            <el-form-item prop="stage" label="收款阶段" size="small">
              <el-select v-model="teamRow.stage" placeholder="请选择">
                <el-option
                  v-for="item in global.stageList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <el-form-item label="备注说明" size="small">
        <el-input type="textarea" v-model="teamRow.remark"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
      <el-button size="small" @click="$emit('closeDialog')">取消</el-button>
    </div>
  </div>
</template>

<script>
  import {
    addProjectContrac,
    deleteProjectContrac,
    getDetails,
    getProjectContracList,
    selectOperator,
    selectProjectContrac,
    selectProjectName,
    updateProjectContrac,
    getBillReceivedInfo
  } from '@/api/projectcontrac'
  import {
    selectTeam
  } from '@/api/contractproject'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const projectName = function(row, column) {
    if (row.projectName) {
      return row.projectName
    } else {
      return row.billName
    }
  }

  const billTime = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const receivingUnit = function(row, column) {
    if (row.receivingUnit) {
      let obj = {}
      obj = global.billUnitList.find((item) => {
        return item.value === row.receivingUnit // 筛选出匹配数据
      })
      return obj.label
    }
  }

  const stage = function(row, column) {
    if (row.stage) {
      let obj = {}
      obj = global.stageList.find((item) => {
        return item.value === row.stage // 筛选出匹配数据
      })
      return obj.label
    }
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    filters: {
      filterStage(stage) {
        let obj = {}
        obj = global.stageList.find((item) => {
          return item.value === stage // 筛选出匹配数据
        })
        return obj.label
      }
    },
    props: ['outerVisible', 'balanceId'],
    data() {
      return {
        colConfigs: [
          { prop: 'projectName', label: '合同项目名称', width: '350', fixed: true, formatter: projectName },
          { prop: 'billAmount', label: '收款金额(万元)', width: '100' },
          { prop: 'actualPay', label: '实到金额(万元)', width: '100' },
          { prop: 'teamName', label: '所属团队', width: '80' },
          { prop: 'contractCode', label: '合同编号', width: '100' },
          { prop: 'contractAmount', label: '合同金额(万元)', width: '100' },
          { prop: 'balancePayment', label: '项目尾款(万元)', width: '100' },
          { prop: 'balancePay', label: '本次尾款(万元)', width: '100' },
          { prop: 'partyA', label: '业主', width: '250' },
          { prop: 'address', label: '项目所属地', width: '150' },
          { prop: 'managementCost', label: '管理费(万元)', width: '100' },
          { prop: 'signatureCost', label: '签字费(万元)', width: '100' },
          { prop: 'auditCost', label: '审核费(万元)', width: '100' },
          { prop: 'otherCost', label: '其他费用(万元)', width: '100' },
          { prop: 'billTime', label: '收款时间', width: '100', component: billTime },
          { prop: 'receivingUnit', label: '收款单位', width: '100', formatter: receivingUnit },
          { prop: 'stage', label: '收款阶段', width: '80', formatter: stage },
          { prop: 'remark', label: '备注说明', width: '160' },
          { slot: 'opt' }
        ],
        searchForm: {
          provinceId: '',
          cityId: ''
        },
        searchFormList: {},
        which: true,
        costTypes: [],
        typeNames: [],
        billAmount: 0,
        listLoading: true,
        dialogTitle: '新增合同到账信息',
        dialogType: 1,
        teamRow: {
          isProject: 1,
          billAmount: 0
        },
        teamRowClear: {
          isProject: 1,
          billAmount: 0
        },
        detail: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        detailVisible: false,
        pca: pca,
        rules: {
          contractCode: [
            { required: true, message: '请输入合同编号', trigger: 'change' }
          ],
          billTime: [
            { required: true, message: '请选择收款时间', trigger: 'change' }
          ],
          billAmount: [
            { required: true, message: '请输入收款金额', trigger: 'change' }
          ],
          receivingUnit: [
            { required: true, message: '请选择收款单位', trigger: 'change' }
          ],
          stage: [
            { required: true, message: '请选择收款阶段', trigger: 'change' }
          ],
          operator: [
            { required: true, message: '请输入收款人', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请输入所属团队', trigger: 'change' }
          ],
          managementFee: [
            { required: true, message: '请输入管理费率', trigger: 'change' }
          ]
        },
        visible: false,
        billReceivedInfo: [],
        isBillReceived: false,
        exportUrl: '' // 导出参数
      }
    },
    created() {
      // this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      // this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      balancePay() {
        let balancePay = this.teamRow.contractAmount || 0
        if (JSON.stringify(this.billReceivedInfo) !== '[]' && this.teamRow.stage) {
          for (let i = 0; i < this.teamRow.stage; i++) {
            this.billReceivedInfo.forEach(value => {
              if (value.stage === i + 1) {
                balancePay = balancePay - value.billAmount
              }
            })
          }
        }
        return Math.round((balancePay + this.billAmount - this.teamRow.billAmount) * 100) / 100
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getProjectContracList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      getBillReceivedInfo(projectId) {
        const params = {
          projectId: projectId
        }
        getBillReceivedInfo(params).then(response => {
          this.billReceivedInfo = response.responseBody
          this.isBillReceived = JSON.stringify(this.billReceivedInfo) !== '[]'
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.billAmount = 0
      },
      editTeam(billId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改合同到账信息'
        this.dialogType = 0
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          billId: billId
        }
        selectProjectContrac(params).then(response => {
          this.teamRow = response.responseBody
          this.billAmount = this.teamRow.billAmount
        })
      },
      getDetail(projectId) {
        this.detailVisible = true
        const params = {
          projectId: projectId
        }
        getDetails(params).then(response => {
          this.detail = response.responseBody
        })
      },
      submitForm(formName) {
        let params = {}
        const managementPercentageCost = Math.round(this.teamRow.managementPercentage * this.teamRow.billAmount * 10000) / 1000000 || 0
        const signatureCost = Math.round(this.teamRow.signature * this.teamRow.billAmount * 10000) / 1000000 || 0
        const auditCost = Math.round(this.teamRow.audit * this.teamRow.billAmount * 10000) / 1000000 || 0
        const otherCost = Math.round(this.teamRow.other * this.teamRow.billAmount * 10000) / 1000000 || 0
        if (this.teamRow.isProject) {
          params = {
            isProject: this.teamRow.isProject,
            projectId: this.teamRow.projectId,
            projectName: this.teamRow.projectName,
            teamId: this.teamRow.teamId,
            teamName: this.teamRow.teamName,
            address: this.teamRow.address,
            contractCode: this.teamRow.contractCode,
            partyA: this.teamRow.partyA,
            contractAmount: this.teamRow.contractAmount,
            balancePayment: this.teamRow.balancePayment,
            balancePay: this.balancePay,
            billTime: this.teamRow.billTime,
            billAmount: this.teamRow.billAmount,
            managementPercentage: this.teamRow.managementPercentage || 0,
            managementCost: managementPercentageCost,
            signatureCost: signatureCost,
            auditCost: auditCost,
            otherCost: otherCost,
            actualPay: this.teamRow.billAmount - managementPercentageCost - signatureCost - auditCost - otherCost,
            receivingUnit: this.teamRow.receivingUnit,
            stage: this.teamRow.stage,
            // operator: this.teamRow.operator,
            remark: this.teamRow.remark || ''
          }
        } else {
          params = {
            isProject: this.teamRow.isProject,
            billName: this.teamRow.billName,
            teamId: this.teamRow.teamId,
            teamName: this.teamRow.teamName,
            billTime: this.teamRow.billTime,
            billAmount: this.teamRow.billAmount,
            managementPercentage: this.teamRow.managementPercentage || 0,
            managementCost: managementPercentageCost,
            signatureCost: 0,
            auditCost: 0,
            otherCost: 0,
            actualPay: this.teamRow.billAmount - managementPercentageCost,
            receivingUnit: this.teamRow.receivingUnit,
            stage: this.teamRow.stage,
            remark: this.teamRow.remark || ''
          }
        }
        if (!this.dialogType) {
          params.billId = this.teamRow.billId
        }
        // 判断balanceId 银行余额登记 与原页面不同
        if (this.balanceId) {
          params.balanceId = this.balanceId
        }

        if (this.teamRow.isProject && !this.teamRow.projectId) {
          this.$message({
            message: '该项目不存在',
            type: 'warning'
          })
        } else if (!this.teamRow.isProject && !this.teamRow.teamId) {
          this.$message({
            message: '该团队不存在',
            type: 'warning'
          })
        } else {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addProjectContrac(params).then(response => {
                  this.addTeam()
                })
              } else {
                updateProjectContrac(params).then(response => {
                  this.addTeam()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          billId: scope.row.billId,
          projectId: scope.row.projectId,
          teamId: scope.row.teamId,
          contractAmount: scope.row.contractAmount,
          isDel: 1
        }
        deleteProjectContrac(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.projectId
        if (queryString) {
          const params = {
            contractCode: queryString
          }
          selectProjectName(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.contractCode
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'projectId', item.projectId)
        this.$set(this.teamRow, 'projectName', item.projectName)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
        this.$set(this.teamRow, 'address', item.address)
        this.$set(this.teamRow, 'partyA', item.partyA)
        this.$set(this.teamRow, 'contractAmount', item.contractAmount)
        this.$set(this.teamRow, 'balancePayment', item.balancePayment)
        this.$set(this.teamRow, 'managementPercentage', item.managementFee)
        this.$set(this.teamRow, 'signature', item.signature)
        this.$set(this.teamRow, 'audit', item.audit)
        this.$set(this.teamRow, 'other', item.other)
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            teamId: this.teamRow.teamId,
            name: queryString
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.name
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectTeam(item) {
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      }
    },
    watch: {
      'teamRow.projectId': {
        handler(newValue, oldValue) {
          this.getBillReceivedInfo(newValue)
        },
        immediate: true
      },
      'searchForm': {
        handler(newValue, oldValue) {
          let exportUrl = ''
          Object.keys(this.searchForm).map((key) => {
            exportUrl += key + '=' + this.searchForm[key] + '&'
          })
          this.exportUrl = exportUrl
        },
        immediate: true,
        deep: true // 深度监听
      },
      'outerVisible': {
        handler(newValue, oldValue) {
          this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
          if (this.$refs['teamRow']) {
            this.$refs['teamRow'].resetFields()
          }
        },
        immediate: true
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .dialog-footer {
    text-align: right;
  }

  .nowrap {
    display: block;
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .row-border {
    margin-bottom: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }

</style>


<style rel="stylesheet/scss" lang="scss">

</style>

